package com.jj.service.player;


import com.jj.core.client.impl.ClientManagerImpl;
import com.jj.dao.entity.User;
import com.jj.dao.repository.UserRepository;
import com.jj.message.PBMessageFactory;
import org.apache.commons.collections4.map.LRUMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Copyrights: QidianGroup@JJ
 *
 * @author: LuHan
 * @date: 2018/1/15, 16:28
 */
@Component
public class PlayerManagerImpl implements PlayerManager{
    private static Logger logger = LoggerFactory.getLogger(PlayerManagerImpl.class);
    private static final int MAX_CACHE_PLAYERS = 50*1024;

    private volatile int maxPlayerId = 1;

    private LRUMap<Long, Player> players = new LRUMap<>(MAX_CACHE_PLAYERS);

    @Autowired
    private ClientManagerImpl clientManager;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PBMessageFactory pbMessageFactory;

    public int getAndIncreasePlayerId(){
        int nextPlayerId = maxPlayerId;
        maxPlayerId++;
        return nextPlayerId;
    }

    @Override
    public Player getPlayer(long uid) {
        synchronized (players){
            Player player = players.get(uid);
            if(player == null){
                player = new PlayerImpl(clientManager, pbMessageFactory);
                player.setUserId(uid);
                player.setId(uid);
                User user = userRepository.findOneByUid(uid);
                Integer characterId = user.getCharacterId();
                if(characterId == null){
                    characterId = 0;
                }
                player.setCharacterId(characterId);
                players.put(uid, player);
                logger.debug("create player {} with id:{}", player.hashCode(), player.getUserId());
            }else{
                logger.debug("already has player {}, hashcode:{}", uid, player.hashCode());
            }
            return player;
        }
    }

    @Override
    public void leave(long uid) {
        players.remove(uid);
    }
}
